package com.situ.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.situ.web.entity.Student;
import com.situ.web.service.IStudentService;
import com.situ.web.service.impl.StudentServiceImpl;

/**
 * Controller层作用：
 * 1、获取界面上的数据，例如add(String name,int age....)，然后封装成Student
 * 2、为界面展示提供数据，例如：List<Student> findAll();
 * 真正完成功能还是要调用Service完成。
 * 后期Controller做的功能会有SprinMVC、Struts2框架帮助我们完成。
 */
//相当于三层架构中的controller层
public class FindAllStudentServlet extends HttpServlet {
	private IStudentService studentService = new StudentServiceImpl();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		ServletContext servletContext = getServletContext();
		int count = (int) servletContext.getAttribute("count");
		count++;
		System.out.println("count: " + count);
		servletContext.setAttribute("count", count);
		
		//1.接收请求参数，封装成对象
		//2.调用业务层进行处理
		List<Student> list = studentService.findAll();
		//3.将处理结果返回给浏览器
		//乱码问题
		//将list学生集合数据放到req中
		req.setAttribute("list", list);
		//转发到jsp页面进行展示
		//存储转发是给服务器看，已经在tomcat下面/Java1812web
		//这个项目下面/student_list.jsp前面的"/"就代表/Java1812Web
		req.getRequestDispatcher("/student_list.jsp").forward(req, resp);
		
		/*resp.setContentType("text/html;charset=utf-8");
		PrintWriter printWriter = resp.getWriter();
		printWriter.println("<table border='1' cellspacing='0'>");
		printWriter.println("<tr>             ");
		printWriter.println("	<th>编号</th> ");
		printWriter.println("	<th>姓名</th> ");
		printWriter.println("	<th>年龄</th> ");
		printWriter.println("	<th>性别</th> ");
		printWriter.println("</tr>            ");
		for (Student student : list) {
			printWriter.println("<tr>             ");
			printWriter.println("	<td>"+student.getId()+"</td>    ");
			printWriter.println("	<td>"+student.getName()+"</td> ");
			printWriter.println("	<td>"+student.getAge()+"</td>   ");
			printWriter.println("	<td>"+student.getGender()+"</td>   ");
			printWriter.println("</tr>            ");
		}
		printWriter.println("</table>");*/
	}

	public static void main(String[] args) {
		IStudentService service = new StudentServiceImpl();
		List<Student> list = service.findAll();
		for (Student student : list) {
			System.out.println(student);
		}
	}
}
